package com.chen.recruit.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * 阿里云oss工具类
 *
 * @author cgy
 * @date 2022/09/04
 */
public class ALiYunOssUtil {

    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static final String ACCESSKEYID = "LTAI5t7HmifSLt6mBEBfU6AS";
    private static final String ACCESSKEYSECRET = "RCLeF3lgYOIVqlnScX7pVhFEuZfoQC";
    private static final String BUCKETNAME = "campus-recruitment";

    /**
     * 文件上传
     */
    public static String uploadFileAvatar(MultipartFile file) {
        // 创建OSS实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType("image/jpg");
        try {
            InputStream inputStream = file.getInputStream();
            int index = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(StrUtil.DOT);
            //获取文件名称
            String fileName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(index);
            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(BUCKETNAME, fileName, inputStream, objectMetadata);
            // 关闭OSSClient。
            ossClient.shutdown();
            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //  https://test123.oss-cn-beijing.aliyuncs.com/01.jpg
            return "https://" + BUCKETNAME + StrUtil.DOT + ENDPOINT + StrUtil.SLASH + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ObjectUtil.isNotNull(ossClient)) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 文件删除
     */
    public static void deleteFileAvatar(String fileName) {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(BUCKETNAME, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ObjectUtil.isNotNull(ossClient)) {
                ossClient.shutdown();
            }
        }
    }
}
